<template>
  <div class="main-container">
    <el-form ref="createForm" :model="dataForm" :rules="rules">
    <!-- 基本配置 -->
    <div class="data-show">
      <!-- 标题 -->
      <div class="data-actions">
        <h3>基本配置</h3>
      </div>
      <!-- 内容区 -->
      <div class="data-table">
        <!-- 通用布局行 -->
        <div class="common-row row-between">
          <!-- 配置项 - 任务名称 -->
          <div class="common-item item-3">
            <label class="condition-label">任务名称</label>
            <el-form-item class="condition-input" prop="name">
              <el-input type="text" placeholder="请输入任务名称" v-model="dataForm.name" />
            </el-form-item>
          </div>
          <!-- 配置项 - el-select-loading -->
          <div class="common-item item-3">
            <label class="condition-label">算法模块选择-selectloading测试</label>
            <el-form-item class="condition-input" prop="system">
              <el-select v-model="dataForm.system" clearable placeholder="请选择平台">
                <el-option v-for="(item, index) in systems" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 配置项 - 类型 -->
          <div class="common-item item-3">
            <label class="condition-label">任务类型</label>
            <el-form-item class="condition-input" prop="system">
              <el-select v-model="dataForm.type" clearable placeholder="请选择类型">
                <el-option v-for="(item, index) in types" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <!-- 通用布局行 -->
        <div class="common-row">
          <div class="common-item item-10">
            <label class="condition-label">任务描述</label>
            <el-form-item class="condition-input" prop="description">
              <el-input v-model="dataForm.description" maxlength="100" type="textarea" show-word-limit :rows="4" resize="none" placeholder="请输入任务描述" />
            </el-form-item>
          </div>
        </div>
      </div>
    </div>
    <!-- 任务上传 -->
    <div class="data-show">
      <!-- 标题 -->
      <div class="data-actions">
        <h3>任务上传</h3>
      </div>
      <!-- 内容区 -->
      <div class="data-table">
        <!-- 通用布局行 - 载体文件stego -->
        <div class="common-row">
          <div class="common-item item-10" :class="{'item-upload': uploadObj.stego.showFileList}">
            <label class="condition-label">载体文件</label>
            <el-form-item class="condition-input" prop="stego">
              <el-upload
                class="upload"
                :ref="uploadObj.uploadRef('stego')"
                drag
                :action="uploadObj.uploadUrl"
                :limit="1"
                :show-file-list="uploadObj.stego.showFileList"
                :before-upload="uploadObj.beforeUpload('stego')"
                :on-success="uploadObj.onSuccess('stego', createForm)"
                :on-progress="uploadObj.onProgress('stego')"
                :on-error="uploadObj.onError('stego')"
                :on-remove="uploadObj.onRemove('stego')"
              >
                <transition name="upload">
                  <div class="upload-empty" v-if="!dataForm.stego">
                    <i class="iconfont icon-icon_update upload-icon"></i>
                    <p class="upload-des">拖拽文件至此或点击上传</p>
                  </div>
                  <div class="upload-content" v-else>
                    <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                    <p class="upload-des">{{ uploadObj.stego.fileName }}</p>
                  </div>
                </transition>
              </el-upload>
            </el-form-item>
          </div>
        </div>
        <!-- 通用布局行 - 任务密钥 -->
        <div class="common-row">
          <div class="common-item item-10" :class="{'item-upload': uploadObj.key.showFileList}">
            <el-tooltip content="切换上传方式" placement="top">
              <label class="condition-label condition-label-change" @click="changeUploadType('key')">任务密钥</label>
            </el-tooltip>
            <el-form-item class="condition-input" prop="key">
              <el-upload
                v-if="uploadObj.key.isUploadType"
                class="upload"
                :ref="uploadObj.uploadRef('key')"
                drag
                :action="uploadObj.uploadUrl"
                :limit="1"
                :show-file-list="uploadObj.key.showFileList"
                :before-upload="uploadObj.beforeUpload('key')"
                :on-success="uploadObj.onSuccess('key', createForm)"
                :on-progress="uploadObj.onProgress('key')"
                :on-error="uploadObj.onError('key')"
                :on-remove="uploadObj.onRemove('key')"
              >
                <transition name="upload">
                  <div class="upload-empty" v-if="!dataForm.key">
                    <i class="iconfont icon-icon_update upload-icon"></i>
                    <p class="upload-des">拖拽文件至此或点击上传</p>
                  </div>
                  <div class="upload-content" v-else>
                    <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                    <p class="upload-des">{{ uploadObj.key.fileName }}</p>
                  </div>
                </transition>
              </el-upload>
              <el-input v-else type="textarea" @change="createBlobTxt($event,'key', createForm)" v-model="uploadObj.key.text" maxlength="255" show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
            </el-form-item>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部的按钮 -->
    <div class="btn-groups">
      <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
      <button type="button" :disabled="createFlag" class="btn" @click="handleCreate">创建</button>
    </div>
    </el-form>
  </div>
</template>
<script setup>
import { ref, onActivated } from 'vue';
import { API } from '@/utils/status.js';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { create } from '@/api/steganography';
import * as rule from '@/utils/rules';
import * as uploadApi from '@/api/file';

const router = useRouter();

// 表单验证规则
const rules = {
  name: rule.taskNameRules
};
const systems = API.steganography.systems;
const types = [
  { value: 0, label: '类型1' },
  { value: 1, label: '类型2' }
];

// ============> data
// 绑定表单对象
const dataForm = ref({
  name: '',
  description: '',
  system: null,
  type: null,
  // 上传属性
  stego: null,
  key: null
});
// 上传控制对象
const uploadObj = ref({
  // uploadUrl: uploadApi.uploadUrl,
  uploadUrl: `${import.meta.env.VITE_FILE_BASE_API}${uploadApi.uploadUrl}`,
  uploadRef(key){
    return function (dom){
      if (dom){
        uploadObj.value[key].dom = dom;
      }
    }
  },
  beforeUpload(key){
    return function (file){
      console.log(file)
      if (uploadObj.value[key].uploading){
        ElMessage.warning('当前有文件正在上传，请稍后重试');
        return false;
      }
      let extension = file.size < API.upload.commonLimit;
      if (!extension) {
        ElMessage.warning(`上传文件超过大小限制，文件须小于${API.upload.commonLimit / (1024 * 1024)}M`)
      }
      if (key === 'key'){
        let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
        extension = fileType == 'txt' ? true : false;
      }
      if (!extension) {
        ElMessage.warning('上传文件须为.txt文件!');
      }
      uploadObj.value[key].fileName = extension ? file.name : '';
      uploadObj.value[key].showFileList = true;
      return extension;
    }
  },
  onSuccess(key, form){
    return function (e){
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      console.log('上传res')
      console.log(e)
      if (e.code === API.code.SUCCESS) { 
        ElMessage.success('上传成功');
        dataForm.value[key] = e.data.path;
      } else {
        let msg = e.msg || e.message || '上传失败，请稍后重试或联系管理员';
        ElMessage({
          type: 'error',
          duration: 1500,
          message: msg
        });
      }
      form.validateField([key])
    }
  },
  onProgress(key){
    return function (e){
      uploadObj.value[key].showFileList = true;
      uploadObj.value[key].uploading = true;
    }
  },
  onError(key){
    return function (e){
      console.log(e)
      let message = e.msg || e.message || '上传失败，请稍后重试或联系管理员'
      ElMessage({
        type: 'error',
        duration: 1500,
        message
      });
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].fileName = '';
    }
  },
  onRemove(key){
    return function (e){
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].fileName = '';
    }
  },
  stego: {
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  key: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  }
});
// 创建按钮点击flag
const createFlag = ref(false);
// 创建任务表单
const createForm = ref(null);
// <============

// ==========> hooks <==========
// todo 这里要在onActived中初始化整个页面的状态对象，如果创建中会一直无法重置
onActivated(() => {

});

// ========> methods <========
// 上传项切换文本 / 上传
function changeUploadType(key){
  uploadObj.value[key].isUploadType = !uploadObj.value[key].isUploadType;
  uploadObj.value[key].text = '';
  uploadObj.value[key].showFileList = false;
  uploadObj.value[key].fileName = '';
  uploadObj.value[key].uploading = false;
}
// 上传项文本输入事件
function createBlobTxt(e, key, form){
  if (!e){
    dataForm.value[key] = '';
    ElMessage.success('上传成功');
    return;
  }
  const blob = new Blob([e], { type: 'text/plain' });
  const txt = new File([blob], 'file.txt', { type: 'text/plain' });
  let formData = new FormData();
  formData.append('file', txt);
  uploadApi.upload(formData)
    .then(res => {
      console.log('上传res')
      ElMessage.success('上传成功');
      dataForm.value[key] = res.path;
      console.log(dataForm.value)
      form.validateField([key]);
    })
    .catch(err => {
      console.log(err)
      let msg = err.msg || err.message || '上传失败，请稍后重试或联系管理员';
      ElMessage.error(msg);
    })
}
// 点击创建按钮
function handleCreate(){
  console.log(dataForm.value)
  if (createFlag.value){
    ElMessage.warning('当前正在创建任务，请稍后重试');
    return;
  }
  createFlag.value = true;
  createForm.value.validate(valid => {
    if (valid) {
      create({
        ...dataForm.value, 
        taskType: API.steganography.type.EXTRACT, 
        moduleType: API.steganography.moduleType.ONE
      })
        .then(res => {
          console.log('创建任务res')
          console.log(res);
          ElMessage.success('创建任务成功！');
          router.back();
          createFlag.value = false;
        })
        .catch(err => {
          console.log(err)
          let message = err.msg || err.messsage || '创建任务失败，请稍后重试或联系管理员';
          ElMessage.err(message);
          createFlag.value = false;
        })
    } else {
      ElMessage.warning('信息填写有误，请核对后提交!');
      createFlag.value = false;
    }
  })
}
// 点击取消按钮
function handleCancel(){
  router.back();
}

</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.row-between {
  justify-content: space-between;
}
.item-3 {
  width: 30%
}
.item-10 {
  width: 100%;
  height: auto;
  padding: 10px 0;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
}
.item-10-spe {
  width: 100%;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
  &::v-deep .el-form-item__content {
    align-items: center!important;
  }
}
.item-5 {
  width: 49%;
  height: auto;
  padding: 50px 0 60px 0;
}
.item-upload {
  padding-bottom: 50px;
}
.upload {
  width: 100%;
  min-height: 120px;
  height: 120px;
  &::v-deep .el-upload {
    @include wh-100;
    // height: 100%!important;
    .el-upload-dragger {
      @include wh-100;
      border-color: var(--color-main);
      padding: 0;
      .upload-empty {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-gray-10);
        }
        .upload-des {
          color: var(--color-gray-10);
        }
      }
      .upload-content {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-main);
        }
        .upload-des {
          color: var(--color-main);
        }
      }
    }
  }
  .el-upload-list {
    margin-top: 0;
  }
}
.btn-groups {
  margin-top: 20px;
  text-align: center;
  .btn {
    margin: 0 20px;
  }
}
.condition-label-change {
  cursor: pointer;
}
.condition-label-change:hover {
  color: var(--color-primary);
}
</style>